//
//  RemoteConfigManager.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/11/5.
//

import FirebaseRemoteConfig

// 统一的Remote Config管理工具类
class RemoteConfigManager {
    static let shared = RemoteConfigManager()
    private let remoteConfig = RemoteConfig.remoteConfig()
    
    private init() {
        setupConfig()
    }
    
    private func setupConfig() {
        // 设置开发模式下的最小获取间隔（调试时设置为0，便于频繁获取）
        #if DEBUG
        let settings = RemoteConfigSettings()
        settings.minimumFetchInterval = 0
        remoteConfig.configSettings = settings
        #endif
        
        // 使用枚举设置默认值
        var defaults: [String: Any] = [:]
        for key in RemoteConfigKey.allCases {
            defaults[key.rawValue] = key.defaultValue
        }
        remoteConfig.setDefaults(defaults as? [String: NSObject])
    }
    
    // 获取配置
    public func fetchConfig(completion: ((Bool) -> Void)? = nil) {
        remoteConfig.fetch { [weak self] (status, error) in
            if status == .success {
                self?.remoteConfig.activate { (changed, error) in
                    completion?(true)
                }
            } else {
                print("配置获取失败: \(error?.localizedDescription ?? "未知错误")")
                completion?(false)
            }
        }
    }
    
    // 类型安全的配置值获取方法
    public func string(for key: RemoteConfigKey) -> String {
        return remoteConfig.configValue(forKey: key.rawValue).stringValue
    }
    
    public func bool(for key: RemoteConfigKey) -> Bool {
        let value = remoteConfig.configValue(forKey: key.rawValue)
        return value.boolValue
    }
    
    public func int(for key: RemoteConfigKey) -> Int {
        let value = remoteConfig.configValue(forKey: key.rawValue)
        return value.numberValue.intValue
    }
    
    public func double(for key: RemoteConfigKey) -> Double {
        let value = remoteConfig.configValue(forKey: key.rawValue)
        return value.numberValue.doubleValue
    }
}
